<template>
  <BasicDrawer
    v-bind="$attrs"
    @register="registerDrawer"
    showFooter
    :title="getTitle"
    width="50%"
    @ok="handleSubmit"
  >
    <BasicForm @register="registerForm" :schemas="schemas">
      <template #productValueDom>
        <BasicTree
          :treeData="treeData"
          :checkable="true"
          ref="asyncExpandTreeRef"
          :replaceFields="replaceFields"
          v-model:checkedKeys="powerList"
          @check="onChangePermissionsTree"
        />
      </template>
    </BasicForm>
  </BasicDrawer>
</template>
<script lang="ts">
import { defineComponent, ref, computed, unref, reactive, toRefs } from 'vue';
import { BasicForm, useForm } from '/@/components/Form/index';
import { BasicTree, TreeActionType } from '/@/components/Tree/index';
import { menuList } from '/@/api/backs/system/role';
import { assignRoleInfo } from '/@/api/backs/system/role';

import { formSchema } from './tableData';
import { BasicDrawer, useDrawerInner } from '/@/components/Drawer';

export default defineComponent({
  name: 'RoleDrawer',
  components: { BasicDrawer, BasicForm, BasicTree },
  props: {
    type: {
      type: String,
      default: () => {
        return 'add';
      },
    },
    powerInfoList: {
      type: Array,
      default: () => {
        return [];
      },
    },
  },
  emits: ['success', 'register'],
  setup(props, { emit }) {
    const isUpdate = ref(true);
    const asyncExpandTreeRef = ref<Nullable<TreeActionType>>(null);
    const data: any = reactive({
      type: 'add',
      schemas: formSchema,
      treeData: [],
      replaceFields: {
        children: 'children',
        title: 'name',
        key: 'id',
      },
      checkedData: [],
      powerList: [],
    });

    const [registerForm, { resetFields, setFieldsValue, resetSchema, setProps, validate }] =
      useForm({
        labelWidth: 100,
        schemas: formSchema,
        showActionButtonGroup: false,
        baseColProps: { lg: 12, md: 24 },
        fieldMapToTime: [['datetime', ['startTime', 'endTime'], 'YYYY-MM-DD']],
      });
    const formId = ref(null);
    const roleId = ref(null);
    const [registerDrawer, { setDrawerProps }] = useDrawerInner(async (data) => {
      resetFields();
      setDrawerProps({ confirmLoading: false });
      isUpdate.value = !!data?.isUpdate;
      formId.value = props.type === 'edit' ? data.record.id : null;
      roleId.value = props.type === 'power' || props.type === 'dataPower' ? data.record.id : null;

      setProps({
        mergeDynamicData: { propsType: props.type },
      });
      data.powerList = [];
      if (unref(isUpdate)) {
        if (data.record.menusIds && data.record.menusIds.length) {
          data.powerList = data.record.menusIds;
        }
        setFieldsValue({
          ...data.record,
          dataScope: data.record.dataScope ? data.record.dataScope + '' : null,
        });
      }
      setCheckedKeys(data.powerList);
      if (props.type === 'power') {
        handlePowerInfo(roleId.value);
      }
    });

    async function handlePowerInfo(id) {
      let powerList = await assignRoleInfo({ roleId: id });
      //设置子节点数据
      setCheckedKeys(powerList);
      return powerList;
    }

    const getTitle = computed(() =>
      props.type === 'edit' ? '编辑' : props.type === 'add' ? '增加' : '设置权限',
    );

    handleMenu();
    // 点击复选框，获取已经选中的复选项id+半选id
    function onChangePermissionsTree(node, event) {
      if (event.halfCheckedKeys) {
        data.checkedData = node.concat(event.halfCheckedKeys);
      } else {
        data.checkedData = node;
      }
    }

    //设置回显的子节点
    function setCheckedKeys(permResult: any) {
      let checkedIds = [] as any;
      permResult.forEach((v) => {
        let result = isChildNode(data.treeData, v);
        if (result) {
          checkedIds.push(v);
        }
      });
      data.powerList = checkedIds;
    }
    //判断是否是子级节点
    function isChildNode(list, id) {
      for (let i = 0; i < list.length; i++) {
        const v = list[i];

        if (id == v.id && !v.children.length) {
          return v.id;
        } else if (v.children) {
          if (isChildNode(v.children, id)) {
            return true;
          }
        }
      }
      return false;
    }

    //获取菜单值
    async function handleMenu() {
      let res = await menuList();
      data.treeData = res;
    }
    async function handleSubmit() {
      try {
        const values = await validate();
        setDrawerProps({ confirmLoading: true });
        let params = { ...values };

        if (data.checkedData.length) {
          params.menuIds = data.checkedData;
        }
        if (roleId.value) {
          params.roleId = roleId.value;
        }
        if (formId.value) {
          params.id = formId.value;
        }
        emit('success', params);
      } finally {
        setDrawerProps({ confirmLoading: false });
      }
    }

    return {
      registerDrawer,
      registerForm,
      getTitle,
      handleSubmit,
      ...toRefs(data),
      asyncExpandTreeRef,
      onChangePermissionsTree,
      setCheckedKeys,
      isChildNode,
    };
  },
});
</script>
<style lang="less" scoped>
::v-deep(.scroll-container) {
  min-height: 600px !important;
  max-height: 600px !important;
}
</style>
